package practise.案例六;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Service {
    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(12345);    // 注册端口
        Socket socket = serverSocket.accept();  // 等待接受连接
//        字符转换流，高级字符缓冲流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        Scanner scanner = new Scanner(System.in);

        String s = "hello" ;
        while (!s.equals("exit")) {
            System.out.println("对方说:"+bufferedReader.readLine());   // 作为服务端，先接收客户端发送过来的消息数据
            System.out.print("我说:");    // 向客户端发送消息
            s = scanner.nextLine();
            bufferedWriter.write(s);    // 输出管道，输出数据到客户端
            bufferedWriter.newLine();
            bufferedWriter.flush(); // 刷新使数据生效
        }
//        关闭资源
        bufferedReader.close();
        bufferedWriter.close();
    }
}
